﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model;
using DAL;
using Common;
using System.IO;
using System.Xml;

namespace BLL
{
    public class BlogBLL
    {
        private BlogDAL dal = new BlogDAL();

        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="extsql">sql条件</param>
        /// <param name="pageIndex">页数</param>
        /// <param name="pageCount">条数</param>
        /// <param name="totalPages">总页数</param>
        /// <param name="totalItems">总条数</param>
        /// <returns></returns>
        public ReturnMessages_Page GetPage(string extsql, int pageIndex, int pageCount)
        {
            ReturnMessages_Page rm = new ReturnMessages_Page();
            try
            {
                int totalPages = 0;
                int totalItems = 0;
                if (pageCount < 10)
                {
                    pageCount = 10;
                }
                rm.code = 200;
                rm.pageindex = pageIndex;
                rm.rows = dal.GetPage(extsql, " blog_addtime desc ", pageIndex, pageCount, ref totalPages, ref totalItems);
                rm.total = totalItems;
                rm.pages = totalPages;
                return rm;
            }
            catch (Exception e)
            {
                rm.code = 500;
                rm.msg = "服务器错误";
                LogHelper.Error(this.GetType().FullName, e.ToString());
                return rm;
            }
        }

        /// <summary>
        /// 获取一条数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Blog GetModel(string id)
        {
            return dal.GetModel(id);
        }

        /// <summary>
        /// 获取自定义数据
        /// </summary>
        /// <param name="columns">列名</param>
        /// <param name="where">条件 </param>
        /// <returns></returns>
        public List<dynamic> GetList(string column, string where)
        {
            return dal.GetList(column, where);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReturnMessages Add(Blog model)
        {
            ReturnMessages rm = new ReturnMessages();
            try
            {
                int count = dal.Add(model);
                if (count > 0)
                {
                    rm.code = 200;
                    rm.msg = "添加成功";
                    UpdateCateAndTagCount();
                    if (model.blog_type == 1)
                    {
                        CreateHTML(model.blog_id);
                    }
                }
                else
                {
                    rm.code = 400;
                    rm.msg = "添加失败,影响行数为0";
                }
            }
            catch(Exception ex)
            {
                rm.code = 500;
                rm.msg = "服务器错误！";
                LogHelper.Error(this.GetType().FullName,ex.ToString());
            }
            return rm;

        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReturnMessages Update(Blog model)
        {
            ReturnMessages rm = new ReturnMessages();
            try
            {
                int count = dal.Update(model);
                if (count > 0)
                {
                    rm.code = 200;
                    rm.msg = "更新成功";
                    UpdateCateAndTagCount();
                    if(model.blog_type==1)
                    {
                        CreateHTML(model.blog_id);
                    }
                }
                else
                {
                    rm.code = 400;
                    rm.msg = "更新失败,影响行数为0";
                }
            }
            catch (Exception ex)
            {
                rm.code = 500;
                rm.msg = "服务器错误！";
                LogHelper.Error(this.GetType().FullName, ex.ToString());
            }
            return rm;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ReturnMessages delete(int id)
        {
            ReturnMessages rm = new ReturnMessages();
            try
            {
                int count = dal.delete(id);
                if (count > 0)
                {
                    rm.code = 200;
                    rm.msg = "删除成功";
                    UpdateCateAndTagCount();
                }
                else
                {
                    rm.code = 400;
                    rm.msg = "删除失败,影响行数为0";
                }
            }
            catch (Exception ex)
            {
                rm.code = 500;
                rm.msg = "服务器错误！";
                LogHelper.Error(this.GetType().FullName, ex.ToString());
            }
            return rm;
        }

        /// <summary>
        /// 异步创建html
        /// </summary>
        /// <param name="blogid"></param>
        private void CreateHTML(int blogid)
        {

            FileStream f = null;
            StreamWriter sw = null;
            try
            {
                string path = Directory.GetCurrentDirectory() + "/wwwroot/html";
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                XmlNodeList xmllist = XmlHelper.ReadNodes(Directory.GetCurrentDirectory() + "/wwwroot/config/fqlblog.config", "configuration");
                string url = xmllist[0].InnerText;
                string html = HttpRequest.Get(url + "/Blog/Model/" + blogid).Result;
                string savepath = path + "/" + blogid + ".html";
                f = new FileStream(savepath, FileMode.Create);
                sw = new StreamWriter(f);
                sw.WriteLine(html);
                sw.Flush();
            }
            catch (Exception ex)
            {
                LogHelper.Error(this.GetType().FullName, ex.ToString());
            }
            finally
            {
                if (sw != null)
                {
                    sw.Dispose();
                }
                if (f != null)
                {
                    f.Dispose();
                }
            }

        }

        /// <summary>
        /// 最近文章(5个)
        /// </summary>
        /// <returns></returns>
        public string RecentBlog()
        {
            List<dynamic> dt = dal.RecentBlog();
            StringBuilder liststr = new StringBuilder();
            for (int i = 0; i < dt.Count; i++)
            {
                liststr.AppendFormat("<li><a title=\"{0}\"  href=\"/html/{1}.html\">{0}</a></li>",Utils.ObjectToStr(dt[i].blog_title), Utils.ObjectToStr(dt[i].blog_id));
            }
            return liststr.ToString();
        }
        /// <summary>
        /// 获取文章数最多的分类（5个）
        /// </summary>
        /// <returns></returns>
        public string BlogCate()
        {
            StringBuilder liststr = new StringBuilder();
            CategoryDAL catedal = new CategoryDAL();
            List<Category> list = catedal.BlogCate();
            foreach (var item in list)
            {
                liststr.AppendFormat("<li><a title=\"{0}\" href=\"/Blog/Cate/{1}\">{0}</a></li>", item.cate_name,Utils.UrlEncode(item.cate_name));
            }
            return liststr.ToString();
        }

        /// <summary>
        /// 热门标签
        /// </summary>
        /// <returns></returns>
        public string HotTag()
        {
            StringBuilder liststr = new StringBuilder();
            TagDAL tagdal = new TagDAL();
            List<Tag> list = tagdal.GetList();
            int max = list.Max<Tag>(m => m.tag_count);//最大指
            int min= list.Min<Tag>(m => m.tag_count);//最小值
            decimal avgpt =Utils.ObjToDecimal(14.00/ (max- min),0);//平均像素
            foreach (var item in list)
            {
                liststr.AppendFormat("<a href='/Blog/Tag/{0}' style='font-size: {1}pt;'>{2}</a>", Utils.UrlEncode(item.tag_name),(item.tag_count- min)*avgpt+8, item.tag_name);
            }
            return liststr.ToString();
        }

        /// <summary>
        /// 更新标签和分类文章数量
        /// </summary>
        public void UpdateCateAndTagCount()
        {
            CategoryBLL catebll = new CategoryBLL();
            TagBLL tagbll = new TagBLL();
            Task.Run(() =>
            {
                tagbll.UpdateTagCount();
                catebll.UpdateCateCount();
            });
        }

        /// <summary>
        /// 生成所有html
        /// </summary>
        /// <returns></returns>
        public ReturnMessages CreateAll()
        {
            ReturnMessages rm = new ReturnMessages();
            try
            {
                List<dynamic> list = dal.GetList("blog_id", " AND `blog_delete`=0 AND blog_type=1 ");
                for (int i = 0; i < list.Count; i++)
                {
                    CreateHTML(Utils.ObjToInt(list[i].blog_id, 0));
                }
                rm.code = 200;
                rm.msg = "正在生成中";
            }
            catch (Exception ex)
            {
                rm.code = 500;
                rm.msg = "生成所有html报错！";
                LogHelper.Error(this.GetType().FullName, ex.ToString());
            }
            return rm;
        }

    }
}
